import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')

import django

django.setup()

import requests
from requests.adapters import HTTPAdapter

# URL: https://build.tarsier-infra.com/packages/mybatis/job_history/openEuler:22.09/openEuler_2209_self/riscv64
# URL: https://build.tarsier-infra.com/build/openEuler:22.09/openEuler_2209_self/riscv64/_jobhistory?package=mybatis

from bs4 import BeautifulSoup
from config import BASE_URL
from obs.models import obs_project, obs_package, obs_job_history
from tqdm import tqdm

session = requests.Session()
session.mount('https://', HTTPAdapter(max_retries=5))

cookies = {
    '_obs_api_session': os.environ['OBS_COOKIE'],
}


def get_job_history(project_name: str, repository_name: str, arch_name: str, package_name: str):
    # url = f'https://build.tarsier-infra.com/packages/{package_name}/job_history/{project_name}/{repository_name}/{arch_name}'
    url = f'{BASE_URL}/build/{project_name}/{repository_name}/{arch_name}/_jobhistory?package={package_name}'

    resp = session.get(url, cookies=cookies, timeout=5)

    parsed = resp.text.replace('\n', '')

    bs = BeautifulSoup(parsed, 'html.parser')
    job_history = []

    try:
        for i in bs.find_all('jobhist'):
            # print(i)
            job = {
                'package_revision': i.get('rev'),
                'build_time': i.get('readytime'),
                'build_reason': i.get('reason'),
                'build_status_code': i.get('code'),
                'build_duration': int(i.get('endtime')) - int(i.get('starttime')),
                'build_worker': i.get('workerid'),
                'versrel': i.get('versrel'),
                'srcmd5': i.get('srcmd5')
            }
            job_history.append(job)
            # for j in i.find_all('td'):
            #     print(j.string, end=', ')
            # print()
    except Exception as e:
        print('Cannot find job history, skipping...', e, file=sys.stderr)

    return job_history


def save_job_history_to_db(project_name: str, package_name: str, job_history: list):
    project = obs_project.objects.get(project_name=project_name)
    package = obs_package.objects.get(project=project, package_name=package_name)

    # exist_job_history = obs_job_history.objects.filter(project=project, package=package).order_by(
    #     '-build_time')
    #
    for line in job_history:
    #     if exist_job_history.filter(build_time=line['build_time']).exists():
    #         return
        obs_job_history.objects.update_or_create(project=project, package=package,
                                       package_revision=line['package_revision'],
                                       build_time=line['build_time'],
                                       build_reason=line['build_reason'],
                                       build_status_code=line['build_status_code'],
                                       build_duration=line['build_duration'],
                                       build_worker=line['build_worker'],
                                       defaults={
                                           'versrel': line['versrel'],
                                           'srcmd5': line['srcmd5']
                                       })


if __name__ == '__main__':
    project_name = os.environ.get('OBS_PROJECT')
    repository_name = os.environ.get('OBS_REPO')
    arch_name = os.environ.get('OBS_ARCH')
    package_name = 'mybatis'

    project = obs_project.objects.get(project_name=project_name)
    packages = obs_package.objects.filter(project=project)

    # jobs = get_job_history(project_name, repository_name, arch_name, package_name)
    # print(jobs)
    # save_job_history_to_db(project_name, package_name, jobs)
    # exit(0)

    for package in tqdm(packages):
        package_name = package.package_name
        # print(package_name)

        try:
            jobs = get_job_history(project_name, repository_name, arch_name, package_name)
            save_job_history_to_db(project_name, package_name, jobs)
        except Exception as e:
            print(e, file=sys.stderr)
